/*
 * 团队回顾 
 */
import 'package:flutter/material.dart';
import 'package:flutter_auth/common/service.dart'; // 服务接口集合
import 'package:flutter_auth/common/picker_tool.dart';
import 'package:flutter_auth/constant/globals.dart' as globals;
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:loading_indicator/loading_indicator.dart';
import 'package:flutter_auth/constants.dart';
import './viewLog.dart'; // 日志查看
import 'package:twinkle_button/twinkle_button.dart';
import './unfilledPer.dart';

class TeamReview extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => TeamReviewState();
}

class TeamReviewState extends State<TeamReview> {
  var userInfo = globals.userInfo['data'];
  String date = ''; // 日期
  List<dynamic> dataSource = []; // 数据源
  bool initLoading = true; // 初始化加载
  List<String> unfilledPer = []; // 未填写人员
  @override
  void initState() {
    var year = DateTime.now().year;
    var month, day;
    if (DateTime.now().month < 10) {
      month = '0${DateTime.now().month.toString()}';
    } else {
      month = DateTime.now().month.toString();
    }
    if (DateTime.now().day < 10) {
      day = '0${DateTime.now().day.toString()}';
    } else {
      day = DateTime.now().day.toString();
    }
    setState(() {
      date = '${year}-${month}-${day}';
    });
    getTeamLogList(); // 获取当日团队回顾
    super.initState();
  }

  /*
   * 获取当日团队回顾 
   */
  void getTeamLogList() {
    setState(() {
      initLoading = true;
    });
    getTeamLogListByUserId({'day': date, 'userId': userInfo['id']})
        .then((result) {
      if (result['state'] && result['data'] != null) {
        List<dynamic> newList = result['data'];
        if (newList.length > 0) {
          newList.add({});
        }
        setState(() {
          dataSource = newList;
          initLoading = false;
          getUsersList(dataSource); // 根据产品线获取用户
        });
      }
    });
  }

  /*
  * 根据产品线获取用户
  */
  void getUsersList(List dataSource) {
    setState(() {
      unfilledPer = [];
    });
    getUsersByProTeam(
            {'proTeam': userInfo['proTeam'], 'userId': userInfo['id']})
        .then((result) {
      if (result['state'] && result['data'] != null) {
        List<String> unList = [];
        List list = result['data'];
        list.forEach((item) {
          bool state = false;
          for (int i = 0, lens = dataSource.length; i < lens; i++) {
            if (dataSource[i]['userId'] == item['id']) {
              state = true;
              break;
            }
          }
          if (!state) {
            unList.add(item['name']);
          }
        });
        setState(() {
          unfilledPer = unList;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('团队回顾'),
        leading: IconButton(
          icon: Icon(Icons.history),
          onPressed: () {
            PickerTool.showDatePicker(
              context,
              dateType: DateType.YMD,
              title: "日期",
              value: date != '' ? DateTime.parse(date) : new DateTime.now(),
              clickCallback: (var str, var time) {
                setState(() {
                  date = str;
                });
                getTeamLogList(); // 获取当日团队回顾
              },
            );
          },
        ),
        actions: _actions(),
      ),
      body: _bodyList(),
      floatingActionButton: _unfilledPer(),
    );
  }

  /*
   * 未填写人员 
   */
  Widget _unfilledPer() {
    if (unfilledPer.length > 0) {
      return Container(
        margin: EdgeInsets.all(2.0), //容器外补白
        child: SizedBox(
          width: 120,
          height: 50,
          child: TwinkleButton(
            buttonTitle: Text(
              '未填写人员',
              style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.w600,
                fontSize: 16.0,
              ),
            ),
            buttonColor: Colors.red,
            onclickButtonFunction: () {
              Navigator.push(context, MaterialPageRoute(builder: (context) {
                return UnfilledPer(items: unfilledPer);
              }));
            },
          ),
        ),
      );
    } else {
      return null;
    }
  }

  Widget _bodyList() {
    if (initLoading == true) {
      return Container(
        alignment: Alignment.center,
        padding: EdgeInsets.all(160.0),
        child: LoadingIndicator(
          indicatorType: Indicator.ballRotateChase,
          color: kPrimaryColor,
        ),
      );
    } else if (dataSource.length == 0) {
      return Container(
        alignment: Alignment.center,
        padding: EdgeInsets.all(16.0),
        child: Text(
          "暂无数据",
          style: TextStyle(
            color: Colors.grey,
            fontSize: 20,
          ),
        ),
      );
    } else if (dataSource.length > 0) {
      return Scrollbar(
        child: ListView.separated(
          itemCount: dataSource.length,
          //列表项构造器
          itemBuilder: (BuildContext context, int index) {
            final Axis slidableDirection = Axis.horizontal;
            if (index == dataSource.length - 1) {
              return Container(
                alignment: Alignment.center,
                padding: EdgeInsets.all(16.0),
                child: Text(
                  "没有更多了",
                  style: TextStyle(color: Colors.grey),
                ),
              );
            }
            return _getSlidableWithLists(context, index, slidableDirection);
          },
          //分割器构造器
          separatorBuilder: (context, index) => Divider(height: 10.0),
        ),
      );
    }
  }

  List<Widget> _actions() {
    List<Widget> actions = [];
    if (date != '') {
      return actions = [
        Container(
          padding: EdgeInsets.only(right: 6.0),
          child: Row(
            children: <Widget>[
              Text(
                date,
                style: TextStyle(
                  fontSize: 18.0,
                  decorationStyle: TextDecorationStyle.dashed,
                ),
              ),
            ],
          ),
        ),
      ];
    } else {
      return actions;
    }
  }

  Widget _getSlidableWithLists(
      BuildContext context, int index, Axis direction) {
    var item = dataSource[index];
    var projectName = dataSource[index]['list'].length > 0
        ? dataSource[index]['list'][0]['projectName']
        : '无';
    /*
  * 列表展示
  */
    List<Widget> _listTileColumn(var item) {
      List<Widget> list = [];
      if (item['trueDate'] != '') {
        list.add(Text("${item['trueDate']}"));
      }
      if (item['userName'] != '') {
        list.add(Text("${item['userName']}"));
      }
      if (item['jobsSuggest'] != '') {
        list.add(Text(
          "${item['jobsSuggest']}",
          softWrap: true,
          maxLines: 3,
          overflow: TextOverflow.ellipsis,
        ));
      }
      if (item['difficultHelp'] != '') {
        list.add(Text(
          "${item['difficultHelp']}",
          softWrap: true,
          maxLines: 3,
          overflow: TextOverflow.ellipsis,
        ));
      }
      return list;
    }

    return Slidable(
      key: Key(item['id'].toString()),
      direction: direction,
      actionExtentRatio: 0.25,
      actionPane: SlidableDrawerActionPane(),
      child: ListTile(
        title: Text("${item['date']}"),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: _listTileColumn(item),
        ),
        onTap: () {
          Navigator.push(context, MaterialPageRoute(builder: (context) {
            return ViewLog(value: item);
          }));
        },
        trailing: Row(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Text('$projectName'),
            Icon(Icons.chevron_right),
          ],
        ),
      ),
    );
  }
}
